<template>
  <el-dialog
    ref="tree"
    v-dialogDrag
    :title="resourceTitle"
    :visible.sync="resourceShow"
    width="60%"
    length="100%"
    :before-close="resourceClose"
  >
    <div style="overflow: auto; overflow-y: auto">
      <el-card
        v-loading="loading"
        shadow="always"
        class="box-card"
        style="overflow: auto"
      >
        <el-tree
          ref="tree"
          node-key="id"
          show-checkbox
          :data="resourceData"
        />
      </el-card>
    </div>
    <span slot="footer">
      <el-button @click="resourceClose">取 消</el-button>
      <el-button type="primary" @click="resourceAdd">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { assignResource } from '../../../api/right/role'
import { treeQuery } from '@/api/right/resource'
export default {
  name: 'ResourcesDialog',
  props: {
    roleId: String, // 角色id
    selections: Array, // 已选择角色
    resourceTitle: String, // 表头标题
    resourceShow: Boolean, // 弹窗是否显示
    resourceClose: Function, // 窗口关闭事件，避免子组件直接修改父组件的参数
    resourceClick: Function // 确认事件，传值给父组件
  },
  data() {
    return {
      resourceData: [],
      roleIdList: [],
      resourceIdList: [],
      resourcedialogType: '',
      loading: true
    }
  },
  // mounted() {
  //   this.onshow()
  // },
  methods: {
    // 转换为资源树
    transform(list) {
      var tree = []
      // 存储一级节点（系统）
      list.map((item) => {
        if (parseInt(item.parentId) === -1 && item.resourceType === 2) {
          tree.push({ label: item.name, id: item.id, children: [] })
        }
      })
      // 存储二级节点（主菜单）
      tree.map((itemParent) => {
        list.map((item) => {
          if (itemParent.id === item.parentId) {
            itemParent.children.push({
              id: item.id,
              label: item.name,
              children: []
            })
          }
        })
      })
      // 存储三级节点（子菜单）
      tree.map((itemParent) => {
        itemParent.children.map((itemSecondParent) => {
          list.map((item) => {
            if (itemSecondParent.id === item.parentId) {
              itemSecondParent.children.push({
                id: item.id,
                label: item.name,
                children: []
              })
            }
          })
        })
      })
      // 存储四级节点（请求权限）
      tree.map((itemParent) => {
        itemParent.children.map((itemSecondParent) => {
          itemSecondParent.children.map((itemthirdParent) => {
            list.map((item) => {
              if (itemthirdParent.id === item.parentId) {
                itemthirdParent.children.push({ id: item.id, label: item.name })
              }
            })
          })
        })
      })
      return tree
    },
    // 获取资源目录
    onshow() {
      const roleVo = this.selections
      const resourceQuery = {}
      resourceQuery.pageSize = 1000
      // 先查询到所有的资源构建出树
      treeQuery(resourceQuery)
        .then((response) => {
          this.resourceData = this.transform(response.data)
          console.log('response.data', response.data)
          for (let i = 0; i < roleVo.length; i++) {
            this.roleIdList.push(roleVo[i].id)
          }
          // 根据角色的id查询到角色所对应的资源进行打钩
          if (roleVo.length === 1) {
            this.fillResourceTree(roleVo[0].id)
          }
        })
    },
    // 用户拥有资源的回填
    fillResourceTree(roleId) {
      console.log(roleId)
      const resourceQuery = {}
      resourceQuery.pageSize = 1000
      resourceQuery.roleId = roleId
      treeQuery(resourceQuery)
        .then((res) => {
          console.log(res)
          for (let i = 0; i < res.data.length; i++) {
            this.$refs.tree.setChecked(res.data[i].id, true, false)
          }
          this
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 对角色进行资源分配
    resourceAdd() {
      if (this.resourceTitle === '资源分配') {
        const list = this.$refs.tree.getCheckedNodes()
        const listParent = this.$refs.tree.getHalfCheckedKeys()
        listParent.map((item) => {
          this.resourceIdList.push(item)
        })
        for (let i = 0; i < list.length; i++) {
          this.resourceIdList.push(list[i].id)
        }
        if (this.resourceIdList == null) {
          if (this.resourcedialogType === 'REVIEW') {
            this.resourcedialogType = ''
          } else { // 构建角色资源对象
            const roleResourceDTO = {
              roleIds: this.roleIdList,
              resourceIds: this.resourceIdList
            }
            console.log('roleResourceDTO', roleResourceDTO)
            // 请求后端接口
            assignResource(roleResourceDTO)
              .then((response) => {
                this.$message({
                  message: '分配成功',
                  type: 'success'
                })
                this.resourceIdList = []
                this.roleIdList = []
                // 进行重新加载
                this.resourceClick()
              })
              .catch(() => {
                this.$message({
                  message: '分配失败',
                  type: 'error'
                })
              })
          }
        } else {
          this.$message({
            message: '无法完成分配操作,必须选择',
            type: 'error'
          })
          this.resourceClick()
        }
      } else {
        this.resourceClick()
      }
    },
    // 查看权限
    look() {
      this.resourcedialogType = 'REVIEW'
      const resourceQuery = {}
      resourceQuery.pageSize = 1000
      treeQuery(resourceQuery).then((response) => {
        // this.resourceData = response.data
        console.log(response.data)
        this.resourceData = this.transform(response.data)
        // 查看权限时，所有树节点全部禁用
        this.resourceData = this.disableTreeNode(this.resourceData)
        this.fillResourceTree(this.roleId)
      })
    },
    // 禁用所有树节点
    disableTreeNode(data) {
      data.map((item) => {
        this.$set(item, 'disabled', true)
        if (item.children && item.children.length > 0) {
          item.children = this.disableTreeNode(item.children)
        }
      })
      return data
    }
  }
}
</script>
